﻿using DevExpress.Mvvm.DataAnnotations;
using DevExpress.Mvvm.POCO;
using JiebaNet.Segmenter;
using Serilog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using TeBigCoreApi;
using TeBigScreenWpf.Common;
using TeBigCommonUI.Items;
using TeBigScreenWpf.WordCloud.TextAnalyses.Blacklist;
using TeBigScreenWpf.WordCloud.TextAnalyses.Processing;
using Timer = System.Timers.Timer;
using DevExpress.XtraLayout.Customization;

namespace TeBigScreenWpf.ViewModels
{
    [POCOViewModel]
    public class vmPage
    {
        public event RoutedEventHandler CaseHeatLoaded;

        #region Config

        public virtual Brush WindowCfg_Background { get; set; } = Themes.MainWindow.Background;
        public virtual Brush Title_Foreground { get; set; } = Themes.MainWindow.Title_Foreground;
        public virtual Brush SubTitle_Foreground { get; set; } = Themes.MainWindow.SubTitle_Foreground;

        #endregion Config

        #region weather icon

        private const string wi_day_sunny = "\uf00d";
        private const string wi_day_cloudy = "\uf002";
        private const string wi_day_cloudy_gusts = "\uf000";
        private const string wi_day_cloudy_windy = "\uf001";
        private const string wi_day_fog = "\uf003";
        private const string wi_day_hail = "\uf004";
        private const string wi_day_haze = "\uf0b6";
        private const string wi_day_lightning = "\uf005";
        private const string wi_day_rain = "\uf008";
        private const string wi_day_rain_mix = "\uf006";
        private const string wi_day_rain_wind = "\uf007";
        private const string wi_day_showers = "\uf009";
        private const string wi_day_sleet = "\uf0b2";
        private const string wi_day_sleet_storm = "\uf068";
        private const string wi_day_snow = "\uf00a";
        private const string wi_day_snow_thunderstorm = "\uf06b";
        private const string wi_day_snow_wind = "\uf065";
        private const string wi_day_sprinkle = "\uf00b";
        private const string wi_day_storm_showers = "\uf00e";
        private const string wi_day_sunny_overcast = "\uf00c";
        private const string wi_day_thunderstorm = "\uf010";
        private const string wi_day_windy = "\uf085";
        private const string wi_solar_eclipse = "\uf06e";
        private const string wi_hot = "\uf072";
        private const string wi_day_cloudy_high = "\uf07d";
        private const string wi_day_light_wind = "\uf0c4";

        private const string wi_night_clear = "\uf02e";
        private const string wi_night_alt_cloudy = "\uf086";
        private const string wi_night_alt_cloudy_gusts = "\uf022";
        private const string wi_night_alt_cloudy_windy = "\uf023";
        private const string wi_night_alt_hail = "\uf024";
        private const string wi_night_alt_lightning = "\uf025";
        private const string wi_night_alt_rain = "\uf028";
        private const string wi_night_alt_rain_mix = "\uf026";
        private const string wi_night_alt_rain_wind = "\uf027";
        private const string wi_night_alt_showers = "\uf029";
        private const string wi_night_alt_sleet = "\uf0b4";
        private const string wi_night_alt_sleet_storm = "\uf06a";
        private const string wi_night_alt_snow = "\uf02a";
        private const string wi_night_alt_snow_thunderstorm = "\uf06d";
        private const string wi_night_alt_snow_wind = "\uf067";
        private const string wi_night_alt_sprinkle = "\uf02b";
        private const string wi_night_alt_storm_showers = "\uf02c";
        private const string wi_night_alt_thunderstorm = "\uf02d";
        private const string wi_night_cloudy = "\uf031";
        private const string wi_night_cloudy_gusts = "\uf02f";
        private const string wi_night_cloudy_windy = "\uf030";
        private const string wi_night_fog = "\uf04a";
        private const string wi_night_hail = "\uf032";
        private const string wi_night_lightning = "\uf033";
        private const string wi_night_partly_cloudy = "\uf083";
        private const string wi_night_rain = "\uf036";
        private const string wi_night_rain_mix = "\uf034";
        private const string wi_night_rain_wind = "\uf035";
        private const string wi_night_showers = "\uf037";
        private const string wi_night_sleet = "\uf0b3";
        private const string wi_night_sleet_storm = "\uf069";
        private const string wi_night_snow = "\uf038";
        private const string wi_night_snow_thunderstorm = "\uf06c";
        private const string wi_night_snow_wind = "\uf066";
        private const string wi_night_sprinkle = "\uf039";
        private const string wi_night_storm_showers = "\uf03a";
        private const string wi_night_thunderstorm = "\uf03b";
        private const string wi_lunar_eclipse = "\uf070";
        private const string wi_stars = "\uf077";
        private const string wi_storm_showers = "\uf01d";
        private const string wi_thunderstorm = "\uf01e";
        private const string wi_night_alt_cloudy_high = "\uf07e";
        private const string wi_night_cloudy_high = "\uf080";
        private const string wi_night_alt_partly_cloudy = "\uf081";

        public static readonly List<string> weather_icon_list = new List<string>
        {
            wi_day_sunny ,
            wi_day_cloudy ,
            wi_day_cloudy_gusts ,
            wi_day_cloudy_windy ,
            wi_day_fog ,
            wi_day_hail ,
            wi_day_haze ,
            wi_day_lightning ,
            wi_day_rain ,
            wi_day_rain_mix ,
            wi_day_rain_wind ,
            wi_day_showers ,
            wi_day_sleet ,
            wi_day_sleet_storm ,
            wi_day_snow ,
            wi_day_snow_thunderstorm ,
            wi_day_snow_wind ,
            wi_day_sprinkle ,
            wi_day_storm_showers ,
            wi_day_sunny_overcast ,
            wi_day_thunderstorm ,
            wi_day_windy ,
            wi_solar_eclipse ,
            wi_hot ,
            wi_day_cloudy_high ,
            wi_day_light_wind ,
            wi_night_clear ,
            wi_night_alt_cloudy ,
            wi_night_alt_cloudy_gusts ,
            wi_night_alt_cloudy_windy ,
            wi_night_alt_hail ,
            wi_night_alt_lightning ,
            wi_night_alt_rain ,
            wi_night_alt_rain_mix ,
            wi_night_alt_rain_wind ,
            wi_night_alt_showers ,
            wi_night_alt_sleet ,
            wi_night_alt_sleet_storm ,
            wi_night_alt_snow ,
            wi_night_alt_snow_thunderstorm ,
            wi_night_alt_snow_wind ,
            wi_night_alt_sprinkle ,
            wi_night_alt_storm_showers ,
            wi_night_alt_thunderstorm ,
            wi_night_cloudy ,
            wi_night_cloudy_gusts ,
            wi_night_cloudy_windy ,
            wi_night_fog ,
            wi_night_hail ,
            wi_night_lightning ,
            wi_night_partly_cloudy ,
            wi_night_rain ,
            wi_night_rain_mix ,
            wi_night_rain_wind ,
            wi_night_showers ,
            wi_night_sleet ,
            wi_night_sleet_storm ,
            wi_night_snow ,
            wi_night_snow_thunderstorm ,
            wi_night_snow_wind ,
            wi_night_sprinkle ,
            wi_night_storm_showers ,
            wi_night_thunderstorm ,
            wi_lunar_eclipse ,
            wi_stars ,
            wi_storm_showers ,
            wi_thunderstorm ,
            wi_night_alt_cloudy_high ,
            wi_night_cloudy_high ,
            wi_night_alt_partly_cloudy,
    };

        #endregion weather icon

        public virtual string WeatherIcon { get; set; } = wi_day_sunny;
        public virtual string WeatherText { get; set; } = "今日有雨\n西风三级\n最高气温31°\n最低气温22°";

        public virtual string DutyText1 { get; set; } = "";
        public virtual string DutyText2 { get; set; } = "";
        public virtual string DutyText3 { get; set; } = "";

        public class DemoGrid
        {
            public string Column1 { get; set; }
            public double Column2 { get; set; }
            public int Column3 { get; set; }
        }

        public class DemoNews
        {
            public string Title { get; set; }
            public string Content { get; set; }
        }

        public class DemoCase : BubbleData<string, int>
        {
            public string Dept
            {
                get => AxisX;
                set => AxisX = value;
            }

            public int Case
            {
                get => AxisY;
                set => AxisY = value;
            }

            public int Feedback { get; set; }
            public int Item1 { get; set; }
            public int Item2 { get; set; }
            public int Item3 { get; set; }
            public int Item4 { get; set; }
            public int Item5 { get; set; }

            public int Item1Item2 { get; set; }
            public int Item1Item2Item3 { get; set; }

            public BureauType Type;
        }

        public class DemoHeat
        {
            public TeBigCommonUI.Items.CoordData Coord { get; set; }

            public float Value { get; set; }
        }

        public class DemoPatrolStat
        {
            public string FDisplayName { get; set; }
            public int FGroupCount { get; set; }
            public int FPatrolCount { get; set; }
            public int FLeftCount { get; set; }
        }

        public class DemoMajorCase
        {
            public string Title { get; set; }

            public string Content => Reference.FContent;

            public DateTime DateTime => Reference.FDate;

            public MajorCaseInfo Reference { get; set; }
        }

        public class DemoCaseHourStat : BubbleData<string, int>
        {
            private DateTime f_datetime;

            public DateTime FDateTime
            {
                get => f_datetime;
                set
                {
                    f_datetime = value;
                    AxisX = f_datetime.Hour.ToString();
                }
            }

            public int FCount
            {
                get => AxisY;
                set => AxisY = value;
            }
        }

        public virtual ObservableCollection<DemoCase> DeptCase { get; set; }

        public virtual double DeptCase_Case_Average { get; set; }
        public virtual double DeptCase_Feedback_Average { get; set; }

        public virtual ObservableCollection<DemoCase> OtherCase { get; set; }

        public virtual ObservableCollection<DemoCase> DeptCaseWeek { get; set; }
        public virtual ObservableCollection<DemoCase> DeptCaseWeek_Item1 { get; set; }
        public virtual ObservableCollection<DemoCase> DeptCaseWeek_Item2 { get; set; }
        public virtual ObservableCollection<DemoCase> DeptCaseWeek_Item3 { get; set; }

        public virtual int DeptCaseWeek_Item1_Average { get; set; }
        public virtual int DeptCaseWeek_Item2_Average { get; set; }
        public virtual int DeptCaseWeek_Item3_Average { get; set; }

        public virtual int WeekCompare0_Item1Item2_Average { get; set; }
        public virtual int WeekCompare1_Item1Item2_Average { get; set; }

        public virtual int WeekCompare0_Item1Item2Item3_Average { get; set; }
        public virtual int WeekCompare1_Item1Item2Item3_Average { get; set; }

        public virtual int WeekCompare0_Item1_Average { get; set; }
        public virtual int WeekCompare1_Item1_Average { get; set; }

        public virtual int WeekCompare0_Item2_Average { get; set; }
        public virtual int WeekCompare1_Item2_Average { get; set; }

        public virtual int WeekCompare0_Item3_Average { get; set; }
        public virtual int WeekCompare1_Item3_Average { get; set; }

        public virtual int WeekCompare0_Feedback_Average { get; set; }
        public virtual int WeekCompare1_Feedback_Average { get; set; }


        public virtual ObservableCollection<DemoCase> WeekCompare0 { get; set; }
        public virtual ObservableCollection<DemoCase> WeekCompare0_Feedback { get; set; }
        public virtual ObservableCollection<DemoCase> WeekCompare0_Item1Item2 { get; set; }
        public virtual ObservableCollection<DemoCase> WeekCompare0_Item1Item2Item3 { get; set; }
        public virtual ObservableCollection<DemoCase> WeekCompare0_Item1 { get; set; }
        public virtual ObservableCollection<DemoCase> WeekCompare0_Item2 { get; set; }
        public virtual ObservableCollection<DemoCase> WeekCompare0_Item3 { get; set; }

        public virtual ObservableCollection<DemoCase> WeekCompare1 { get; set; }
        public virtual ObservableCollection<DemoCase> WeekCompare1_Feedback { get; set; }
        public virtual ObservableCollection<DemoCase> WeekCompare1_Item1Item2 { get; set; }
        public virtual ObservableCollection<DemoCase> WeekCompare1_Item1Item2Item3 { get; set; }
        public virtual ObservableCollection<DemoCase> WeekCompare1_Item1 { get; set; }
        public virtual ObservableCollection<DemoCase> WeekCompare1_Item2 { get; set; }
        public virtual ObservableCollection<DemoCase> WeekCompare1_Item3 { get; set; }

        public virtual ObservableCollection<CaseReason> CaseReason { get; set; }

        public virtual ObservableCollection<TeamStat> CallStat { get; set; }

        public virtual ObservableCollection<TeamOperator> Operator { get; set; }

        public virtual ObservableCollection<CaseGroupStat> CaseAllStat { get; set; }

        public virtual ObservableCollection<CaseGroupStat> CaseAllDisplay { get; set; }

        public virtual ObservableCollection<DemoPatrolStat> DeptPatrol { get; set; }

        public virtual ObservableCollection<PatrolStat> PatrolStat { get; set; }

        public virtual ObservableCollection<CaseXY> CaseHeat { get; set; }
        public virtual ObservableCollection<CaseXY> CaseXY10 { get; set; }
        public virtual ObservableCollection<CaseXY> CaseXY20 { get; set; }
        public virtual ObservableCollection<CaseXY> CaseXY30 { get; set; }

        public virtual ObservableCollection<DemoCaseHourStat> CaseHourStat { get; set; }

        public virtual ObservableCollection<CaseDetailStat> CaseDetailStat10 { get; set; }
        public virtual ObservableCollection<CaseDetailStat> CaseDetailStat20 { get; set; }

        public virtual IEnumerable<IWord> HotWords { get; set; }

        public QueryPatrolStatResponse PatrolResponse { get; set; } = null;

        public static readonly string FooterTitleDefault = "大庆市公安局";

        public virtual string FooterTitle { get; set; } = FooterTitleDefault;

        public virtual int CaseCountAll { get; set; }

        public virtual int CaseCountDeal { get; set; }

        public virtual int CaseCountFeedback { get; set; }

        public void ToggleFooter()
        {
            if (PatrolResponse != null)
            {
                List<PatrolStat> tmp = null;

                if (FooterTitle != FooterTitleDefault)
                {
                    tmp = PatrolResponse.AreaStat.Where(r => r.Reference != null && r.Reference.FDeptName == FooterTitle).ToList();
                }

                if (tmp == null || tmp.Count == 0)
                    tmp = PatrolResponse.DeptStat.ToList();

                PatrolStat = tmp.OrderByList(DeptInfoManager.order_patrol, (a, b) => a.FDisplayName == b).ToObservableCollection();
            }
        }

        public virtual PatrolStat PatrolCurrent { get; set; }

        public virtual List<DemoMajorCase> MajorCase { get; set; }

        public virtual HashSet<CaseXY[]> HeatClusters { get; set; }

        public static vmPage Create()
        {
            return ViewModelSource.Create(() => new vmPage());
        }

        private Timer m_timer_quick = new Timer(TimeSpan.FromSeconds(10).TotalMilliseconds);
        private Timer m_timer_slow = new Timer(TimeSpan.FromMinutes(10).TotalMilliseconds);

        protected vmPage()
        {
            m_timer_quick.AutoReset = false;
            m_timer_quick.Elapsed += Timer_Quick_Elapsed;

            m_timer_slow.AutoReset = false;
            m_timer_slow.Elapsed += Timer_Slow_Elapsed;

            LoadData();
        }

        private void Timer_Slow_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            LoadData(false, true);
        }

        private void Timer_Quick_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            LoadData(true, false);
        }

        private List<DemoCase> CreateWeekCompare(IList<CaseDeptStat> origin)
        {
            var list = new List<DemoCase>();

            var sum = origin.Sum(r => r.FCount);

            var g = origin.GroupBy(r => DeptInfoManager.GetBureauCode(r.FDeptCode));

            foreach (var item in g)
            {
                list.Add(new DemoCase
                {
                    Dept = DeptInfoManager.GetBureauName(item.Key),
                    Type = DeptInfoManager.GetBureauType(item.Key),
                    Case = item.Sum(r => r.FCount),
                    Weight = item.Sum(r => r.FCount) * 1.0 / sum,
                    Feedback = item.Sum(r => r.FFeedback),
                    Item1 = item.Where(r => r.FTypeCode == Constant.Type_刑事).Sum(r => r.FCount),
                    Item2 = item.Where(r => r.FTypeCode == Constant.Type_治安).Sum(r => r.FCount),
                    Item3 = item.Where(r => r.FTypeCode == Constant.Type_交通).Sum(r => r.FCount),

                    Item1Item2 = item.Where(r => r.FTypeCode == Constant.Type_刑事 || r.FTypeCode == Constant.Type_治安).Sum(r => r.FCount),
                    Item1Item2Item3 = item.Where(r => r.FTypeCode == Constant.Type_刑事 || r.FTypeCode == Constant.Type_治安 || r.FTypeCode == Constant.Type_交通).Sum(r => r.FCount),
                });
            }

            return list;
        }

        private List<DemoCase> CreateDemoCase(IList<CaseDeptStat> origin)
        {
            var list = new List<DemoCase>();

            var sum = origin.Sum(r => r.FCount);

            var g = origin.GroupBy(r => DeptInfoManager.GetBureauCode(r.FDeptCode));

            foreach (var item in g)
            {
                list.Add(new DemoCase
                {
                    Dept = DeptInfoManager.GetBureauName(item.Key),
                    Type = DeptInfoManager.GetBureauType(item.Key),
                    Case = item.Sum(r => r.FCount),
                    Weight = item.Sum(r => r.FCount) * 1.0 / sum,
                    Feedback = item.Sum(r => r.FFeedback),
                    Item1 = item.Where(r => r.FTypeCode == Constant.Type_刑事).Sum(r => r.FCount),
                    Item2 = item.Where(r => r.FTypeCode == Constant.Type_治安).Sum(r => r.FCount),
                    Item3 = item.Where(r => r.FTypeCode == Constant.Type_交通).Sum(r => r.FCount),
                    Item4 = item.Where(r => r.FTypeCode == Constant.Type_联动).Sum(r => r.FCount),
                    Item5 = item.Where(r => r.FTypeCode == Constant.Type_其他).Sum(r => r.FCount),
                });
            }

            return list;
        }

        private List<DemoMajorCase> CreateMajorCase(IList<MajorCaseInfo> list)
        {
            var resp = new List<DemoMajorCase>();

            foreach (var item in list)
            {
                resp.Add(new DemoMajorCase
                {
                    Reference = item,
                    Title = DeptInfoManager.GetSimpleBureauName(item.FDeptCode),
                });
            }

            return resp;
        }

        private void CreateDeptPatrol(ObservableCollection<PatrolAreaStat> list)
        {
            var resp = new List<DemoPatrolStat>();

            resp.AddRange(list.GroupBy(r => r.FDeptCode).Select(r => new DemoPatrolStat
            {
                FDisplayName = r.First().FDeptName,
                FGroupCount = r.Sum(k => k.FGroupCount),
                FPatrolCount = r.Sum(k => k.FPatrolCount),
                FLeftCount = r.Sum(k => k.FLeftCount),
            }));

            DeptPatrol = resp.OrderByList(DeptInfoManager.order_patrol, (a, b) => a.FDisplayName == b).ToObservableCollection();
        }

        //中文分词
        public static class JiebaWrapper
        {
            private class BlackList : IBlacklist
            {
                public HashSet<string> FilterWords = new HashSet<string>()
                {
                    "路口","转盘","交叉口","附近","门前","楼下","号楼","对面","大队","小区","路上",
                    "报警", "警情", "不详","人称","有人","发生","但是", "已经","拨打","接到",
                    "无人","一辆","两辆","人员","正在","现在","当前","关联","重复", "自己","告知",
                    "信息", "事宜","价值","民警","反馈","讲话","对方","挂断","电话","反映","需要",
                    "大庆", "分局","是否","一个","两个","测试","拨测","无法","没有","人要","或者",
                    "一会","一台","一路","一起","一名","一部","之间","一位","一直",
                    "人想", "之前","称要","称其","后称","不到",
                };

                public int Count => FilterWords.Count;

                public bool Countains(string word)
                {
                    if (FilterWords.Contains(word))
                        return true;

                    if (word.Length == 1)
                        return true;

                    if (double.TryParse(word, out var _))
                        return true;

                    return false;
                }
            }

            private static List<string> NewWords = new List<string>
            {
                "萨尔图", "卧里屯", "让胡路", "广源市场"
            };

            private static Lazy<JiebaSegmenter> m_segmenter = new Lazy<JiebaSegmenter>(CreateSegmenter);

            private static JiebaSegmenter CreateSegmenter()
            {
                var segmenter = new JiebaSegmenter();

                foreach (var item in NewWords)
                {
                    segmenter.AddWord(item);
                }

                return segmenter;
            }

            public static IEnumerable<IWord> CutWords(IList<CaseContent> list)
            {
                List<string> words = new List<string>();

                var blacklist = new BlackList();

                foreach (var item in list)
                {
                    var cc = item.FContent;
                    var seg = m_segmenter.Value.Cut(cc);

                    words.AddRange(seg);
                }

                return words.Filter(blacklist).CountOccurences();
            }
        }

        private void Dbscan(IList<CaseXY> list)
        {
            double get_distance(CaseXY lhs, CaseXY rhs)
            {
                return GeoUtils.Distance(lhs.Longitude, lhs.Latitude, rhs.Longitude, rhs.Latitude);
            }

            GeoUtils.Dbscan(list, get_distance, 1000, 2, out HashSet<CaseXY[]> clusters);
        }

        //接警员, 班组
        private async void LoadData1(DateTime begin, DateTime end)
        {
            try
            {
                var ret = await TeBigCoreService.Today.QueryTeamAsync(new QueryTeamRequest());

                if (ret.IsSuccess)
                {
                    CallStat = new ObservableCollection<TeamStat> { ret.Team };

                    Operator = ret.Peoples;
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        //今日案由
        private async void LoadData2(DateTime begin, DateTime end)
        {
            try
            {
                var ret = await TeBigCoreService.Today.QueryCaseReasonAsync(new QueryCaseReasonRequest
                {
                    Begin = begin,
                    End = end,
                });

                if (ret.IsSuccess)
                {
                    CaseReason = ret.List.OrderByDescending(r => r.FCount)
                        //.Where(r => r.FReasonCode != "609900")
                        //.Where(r => r.FReasonCode != "999900")
                        //.Where(r => r.FReasonCode != "500500")
                        .Take(20).OrderBy(r => r.FReasonCode)
                        .ToObservableCollection();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        //今日警情
        private async void LoadData3(DateTime begin, DateTime end)
        {
            try
            {
                var ret = await TeBigCoreService.Today.QueryCaseStatAsync(new QueryCaseStatRequest
                {
                    Begin = begin,
                    End = end,
                });

                if (ret.IsSuccess)
                {
                    var dp = CreateDemoCase(ret.List).OrderByList(DeptInfoManager.order_dept110, (a, b) => a.Dept == b);

                    var list = ret.List.Where(r => r.FTypeCode != Constant.Type_投诉).ToList();

                    CaseCountAll = list.Sum(r => r.FCount);
                    CaseCountDeal = list.Sum(r => r.FDeal);
                    CaseCountFeedback = list.Sum(r => r.FFeedback);

                    DeptCase = dp.Where(r => r.Type.HasFlag(BureauType.FenJu)).ToObservableCollection();

                    DeptCase_Case_Average = DeptCase.Average(r => r.AxisY);
                    DeptCase_Feedback_Average = DeptCase.Average(r => r.Feedback);

                    CaseAllStat = ret.AllStat.ToObservableCollection();

                    CaseAllDisplay = ret.AllStat.Where(r => r.FTypeCode != Constant.Type_投诉).ToObservableCollection();

                    foreach (var item in CaseAllDisplay)
                    {
                        item.FDisplayName = ReplaceName(item.FDisplayName);
                    }

                    CaseAllDisplay.Insert(0, new CaseGroupStat
                    {
                        FDisplayName = "今日警情",
                        FCount = CaseAllDisplay.Sum(r => r.FCount)
                    });
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        private string ReplaceName(string fDisplayName)
        {
            if (fDisplayName != "其他警情")
            {
                return fDisplayName.Replace("警情", "");
            }

            return fDisplayName;
        }

        //一周警情
        private async void LoadData4(DateTime begin, DateTime end)
        {
            try
            {
                var ret = await TeBigCoreService.Today.QueryCaseStatAsync(new QueryCaseStatRequest
                {
                    Begin = end.AddDays(-7),
                    End = end,
                });

                if (ret.IsSuccess)
                {
                    var dp = CreateDemoCase(ret.List);

                    var week = dp.Where(r => r.Type.HasFlag(BureauType.FenJu))
                        .OrderByList(DeptInfoManager.order_dept110, (a, b) => a.Dept == b)
                        .ToList();

                    DeptCaseWeek_Item1 = week.Where(r => r.Item1 > 0).ToObservableCollection();
                    DeptCaseWeek_Item2 = week.Where(r => r.Item2 > 0).ToObservableCollection();

                    DeptCaseWeek_Item3 = dp.Where(r => r.Type.HasFlag(BureauType.JiaoJing))
                        .Where(r => r.Item3 > 0)
                        .OrderByList(DeptInfoManager.order_dept122, (a, b) => a.Dept == b)
                        .ToObservableCollection();

                    DeptCaseWeek_Item1_Average = Convert.ToInt32(DeptCaseWeek_Item1.Average(r => r.Item1));
                    DeptCaseWeek_Item2_Average = Convert.ToInt32(DeptCaseWeek_Item2.Average(r => r.Item2));
                    DeptCaseWeek_Item3_Average = Convert.ToInt32(DeptCaseWeek_Item3.Average(r => r.Item3));
                }

                if (ret.IsSuccess)
                {
                    WeekCompare0 = CreateWeekCompare(ret.List)
                        .OrderByList(DeptInfoManager.order_dept110, (a, b) => a.Dept == b)
                        .ToObservableCollection();

                    WeekCompare0_Feedback = WeekCompare0.Where(r => r.Type.HasFlag(BureauType.FenJu)).ToObservableCollection();

                    WeekCompare0_Item1Item2 = WeekCompare0.Where(r => r.Type.HasFlag(BureauType.FenJu))
                       .Where(r => r.Item1Item2 > 0)
                       .OrderByList(DeptInfoManager.order_dept110, (a, b) => a.Dept == b)
                       .ToObservableCollection();

                    WeekCompare0_Item1Item2Item3 = WeekCompare0
                        .Where(r => r.Type.HasFlag(BureauType.FenJu) || r.Type.HasFlag(BureauType.JiaoJing))
                        .Where(r => r.Item1Item2Item3 > 0)
                        .OrderByList(DeptInfoManager.order_dept_110_122, (a, b) => a.Dept == b)
                        .ToObservableCollection();

                    WeekCompare0_Item1 = WeekCompare0.Where(r => r.Type.HasFlag(BureauType.FenJu))
                        .Where(r => r.Item1 > 0)
                        .OrderByList(DeptInfoManager.order_dept110, (a, b) => a.Dept == b)
                        .ToObservableCollection();

                    WeekCompare0_Item2 = WeekCompare0.Where(r => r.Type.HasFlag(BureauType.FenJu))
                       .Where(r => r.Item2 > 0)
                       .OrderByList(DeptInfoManager.order_dept110, (a, b) => a.Dept == b)
                       .ToObservableCollection();

                    WeekCompare0_Item3 = WeekCompare0.Where(r => r.Type.HasFlag(BureauType.JiaoJing))
                        .Where(r => r.Item3 > 0)
                        .OrderByList(DeptInfoManager.order_dept122, (a, b) => a.Dept == b)
                        .ToObservableCollection();


                    WeekCompare0_Item1Item2_Average = Convert.ToInt32(WeekCompare0_Item1Item2.Average(r => r.Item1Item2));
                    WeekCompare0_Item1Item2Item3_Average = Convert.ToInt32(WeekCompare0_Item1Item2Item3.Average(r => r.Item1Item2Item3));
                    WeekCompare0_Item1_Average = Convert.ToInt32(WeekCompare0_Item1.Average(r => r.Item1));
                    WeekCompare0_Item2_Average = Convert.ToInt32(WeekCompare0_Item2.Average(r => r.Item2));
                    WeekCompare0_Item3_Average = Convert.ToInt32(WeekCompare0_Item3.Average(r => r.Item3));
                    WeekCompare0_Feedback_Average = Convert.ToInt32(WeekCompare0_Feedback.Average(r => r.Feedback));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        //上一周警情
        private async void LoadData5(DateTime begin, DateTime end)
        {
            try
            {
                var ret = await TeBigCoreService.Today.QueryCaseStatAsync(new QueryCaseStatRequest
                {
                    Begin = end.AddDays(-14),
                    End = end.AddDays(-7),
                });

                if (ret.IsSuccess)
                {
                    WeekCompare1 = CreateWeekCompare(ret.List)
                        .OrderByList(DeptInfoManager.order_dept110, (a, b) => a.Dept == b)
                        .ToObservableCollection();

                    WeekCompare1_Feedback = WeekCompare1.Where(r => r.Type.HasFlag(BureauType.FenJu)).ToObservableCollection();

                    WeekCompare1_Item1Item2 = WeekCompare1.Where(r => r.Type.HasFlag(BureauType.FenJu))
                         .Where(r => r.Item1Item2 > 0)
                         .OrderByList(DeptInfoManager.order_dept110, (a, b) => a.Dept == b)
                         .ToObservableCollection();

                    WeekCompare1_Item1Item2Item3 = WeekCompare1
                        .Where(r => r.Type.HasFlag(BureauType.FenJu) || r.Type.HasFlag(BureauType.JiaoJing))
                        .Where(r => r.Item1Item2Item3 > 0)
                        .OrderByList(DeptInfoManager.order_dept_110_122, (a, b) => a.Dept == b)
                        .ToObservableCollection();

                    WeekCompare1_Item1 = WeekCompare1.Where(r => r.Type.HasFlag(BureauType.FenJu))
                        .Where(r => r.Item1 > 0)
                        .OrderByList(DeptInfoManager.order_dept110, (a, b) => a.Dept == b)
                        .ToObservableCollection();

                    WeekCompare1_Item2 = WeekCompare1.Where(r => r.Type.HasFlag(BureauType.FenJu))
                        .Where(r => r.Item2 > 0)
                        .OrderByList(DeptInfoManager.order_dept110, (a, b) => a.Dept == b)
                        .ToObservableCollection();

                    WeekCompare1_Item3 = WeekCompare1.Where(r => r.Type.HasFlag(BureauType.JiaoJing))
                        .Where(r => r.Item3 > 0)
                        .OrderByList(DeptInfoManager.order_dept122, (a, b) => a.Dept == b)
                        .ToObservableCollection();

                    WeekCompare1_Item1Item2_Average = Convert.ToInt32(WeekCompare1_Item1Item2.Average(r => r.Item1Item2));
                    WeekCompare1_Item1Item2Item3_Average = Convert.ToInt32(WeekCompare1_Item1Item2Item3.Average(r => r.Item1Item2Item3));
                    WeekCompare1_Item1_Average = Convert.ToInt32(WeekCompare1_Item1.Average(r => r.Item1));
                    WeekCompare1_Item2_Average = Convert.ToInt32(WeekCompare1_Item2.Average(r => r.Item2));
                    WeekCompare1_Item3_Average = Convert.ToInt32(WeekCompare1_Item3.Average(r => r.Item3));
                    WeekCompare1_Feedback_Average = Convert.ToInt32(WeekCompare1_Feedback.Average(r => r.Feedback));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        //今日巡逻警力
        private async void LoadData6(DateTime begin, DateTime end)
        {
            try
            {
                PatrolResponse = await TeBigCoreService.Today.QueryPatrolStatAsync(new QueryPatrolStatRequest());

                if (PatrolResponse.IsSuccess)
                {
                    CreateDeptPatrol(PatrolResponse.List);

                    ToggleFooter();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        //重要案情
        private async void LoadData7(DateTime begin, DateTime end)
        {
            try
            {
                var resp = await TeBigCoreService.Today.QueryCaseInfoAsync(new QueryCaseInfoRequest
                {
                    Begin = DateTime.Now.AddDays(-1),
                    End = DateTime.Now
                });

                if (resp.IsSuccess)
                {
                    MajorCase = CreateMajorCase(resp.List);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        //警情细类 - 刑事
        private async void LoadData8(DateTime begin, DateTime end)
        {
            try
            {
                var resp = await TeBigCoreService.Today.QueryCaseDetailStatAsync(new QueryCaseDetailStatRequest
                {
                    Begin = begin,
                    End = end,
                    TypeCode = Constant.Type_刑事,
                });

                if (resp.IsSuccess)
                {
                    CaseDetailStat10 = resp.List;
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        //警情细类 - 治安
        private async void LoadData9(DateTime begin, DateTime end)
        {
            try
            {
                var resp = await TeBigCoreService.Today.QueryCaseDetailStatAsync(new QueryCaseDetailStatRequest
                {
                    Begin = begin,
                    End = end,
                    TypeCode = Constant.Type_治安,
                });

                if (resp.IsSuccess)
                {
                    CaseDetailStat20 = resp.List;
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        //警情撒点
        private async void LoadData10(DateTime begin, DateTime end)
        {
            try
            {
                var ret = await TeBigCoreService.Today.QueryCaseXYAsync(new QueryCaseXYRequest()
                {
                    Begin = begin,
                    End = end,
                });

                if (ret.IsSuccess)
                {
                    CaseXY10 = ret.List.Where(r => r.FTypeCode == Constant.Type_刑事).ToObservableCollection();
                    CaseXY20 = ret.List.Where(r => r.FTypeCode == Constant.Type_治安).ToObservableCollection();
                    CaseXY30 = ret.List.Where(r => r.FTypeCode == Constant.Type_交通).ToObservableCollection();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        //关键词
        private async void LoadData11(DateTime begin, DateTime end)
        {
            try
            {
                var ret = await TeBigCoreService.Today.QueryCaseContentAsync(new QueryCaseContentRequest()
                {
                    Begin = end.AddDays(-3),
                    End = end,
                });

                if (ret.IsSuccess)
                {
                    HotWords = JiebaWrapper.CutWords(ret.List);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        //热力图
        private async void LoadData12(DateTime begin, DateTime end)
        {
            try
            {
                var ret = await TeBigCoreService.Today.QueryCaseXYAsync(new QueryCaseXYRequest()
                {
                    Begin = end.AddDays(-3),
                    End = end,
                });

                if (ret.IsSuccess)
                {
                    CaseHeat = ret.List;

                    CaseHeatLoaded?.Invoke(this, new RoutedEventArgs());
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        //二十四小时案情
        private async void LoadData13()
        {
            try
            {
                var now = DateTime.Now;
                var request_end = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0).AddHours(1);

                var ret = await TeBigCoreService.Today.QueryCaseHourStatAsync(new QueryCaseHourStatRequest()
                {
                    Begin = request_end.AddDays(-1),
                    End = request_end
                });

                if (ret.IsSuccess)
                {
                    double all = ret.List.Sum(r => r.FCount);

                    CaseHourStat = ret.List.Select(r => new DemoCaseHourStat
                    {
                        FCount = r.FCount,
                        FDateTime = r.FDateTime,
                        Weight = r.FCount / all
                    }).ToObservableCollection();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        private void LoadData(bool quick = true, bool slow = true)
        {
            var dt_today = DateTime.Today;
            var dt_boundary = new DateTime(dt_today.Year, dt_today.Month, dt_today.Day, 6, 0, 0);

#if DEBUG
            var begin = new DateTime(DateTime.Today.Year, 7, 20, 6, 0, 0);
#else
            var begin = DateTime.Now < dt_boundary ? dt_boundary.AddDays(-1) : dt_boundary;
#endif
            var end = begin.AddDays(1);

            if (quick)
                LoadDataQuick(begin, end);

            if (slow)
                LoadDataSlow(begin, end);
        }

        private void LoadDataQuick(DateTime begin, DateTime end)
        {
            //接警员, 班组
            LoadData1(begin, end);

            //今日案由
            LoadData2(begin, end);

            //今日警情
            LoadData3(begin, end);

            //今日巡逻警力
            LoadData6(begin, end);

            //重要案情
            LoadData7(begin, end);

            //警情细类 - 刑事
            LoadData8(begin, end);

            //警情细类 - 治安
            LoadData9(begin, end);

            //警情撒点
            LoadData10(begin, end);

            m_timer_quick.Start();
        }

        private void LoadDataSlow(DateTime begin, DateTime end)
        {
            //一周警情
            LoadData4(begin, end);

            //上一周警情
            LoadData5(begin, end);

           

            //关键词
            LoadData11(begin, end);

            //热力图
            LoadData12(begin, end);

            //二十四小时案情
            LoadData13();

            m_timer_slow.Start();
        }
    }
}